<template>
  <div class="container"> <!-- 外层容器 -->
    <div class="left-container"> <!-- K线图容器 -->
      <div class="Kpicture">
        <div class="pictureClassfiy">
          <div @click="ChangePicture(1)" :class="showKPicture === 1 ? 'active-border' : 'normal-border'">日K线</div>
          <div @click="ChangePicture(2)" :class="showKPicture === 2 ? 'active-border' : 'normal-border'">周K线</div>
          <div @click="ChangePicture(3)" :class="showKPicture === 3 ? 'active-border' : 'normal-border'">月K线</div>
        </div>
        <div class="Picture">
          <div ref="chartDom" class="PictureContent"></div>
        </div>
      </div>
    </div>

    <div class="right-container"> <!-- 推荐新闻容器 -->
      <div class="recommend-container">
        <div class="recommendSection">
          <h3>推荐新闻</h3>
          <ul class="recommendList">
            <li v-for="(news, index) in recommendedNews" :key="index" @click="goToNewsDetail(news.id)">
              <div>
                <div class="recommendTitle">{{`${index+1}. ${news.title}` }}</div>
                <div class="recommendTime">{{ news.publishDate }}</div>
              </div>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- 股票信息管理容器 -->
  <div class="stock-management-container">
    <h3>自选股票</h3>
    <div class="filter">
      <el-input style="width: 30%;" v-model="searchQuery" placeholder="输入股票名称或股票代码" prefix-icon="el-icon-search" />
    </div>

    <!-- 自选股列表 -->
    <el-table :data="filteredStocks" :row-style='rowStyle' @row-click="ToStockMessagePage" border v-model:empty-text="emptyMessage">
      <el-table-column label="股票名称"  prop="name"></el-table-column>
      <el-table-column label="股票代码" prop="ts_code"></el-table-column>
      <el-table-column label="交易时间" prop="date"></el-table-column>
      <el-table-column label="现价" prop="price">
        <template #default="scope">
          <span v-if="scope.row.status === 'up'" style="color: red;">{{ scope.row.price }}</span>
          <span v-else-if="scope.row.status === 'down'" style="color: green;">{{ scope.row.price }}</span>
          <!-- 可添加更多条件判断 -->
          <span v-else>{{ scope.row.price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="涨跌额">
        <template #default="scope">
          <span v-if="scope.row.status === 'up'" style="color: red;">{{ formatRatio(scope.row) }}</span>
          <span v-else-if="scope.row.status === 'down'" style="color: green;">{{ formatRatio(scope.row) }}</span>
          <!-- 可添加更多条件判断 -->
          <span v-else>{{ formatRatio(scope.row) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="开盘价" prop="open"></el-table-column>
      <el-table-column label="昨收价" prop="pre_close"></el-table-column> -->
      <el-table-column label="最高价" prop="high"></el-table-column>
      <el-table-column label="最低价" prop="low"></el-table-column>

      <!-- <el-table-column label="增长值" prop="increase"></el-table-column> -->
      <!-- <el-table-column label="成交金额" prop="amount"></el-table-column> -->
      <!-- <el-table-column label="成交量" prop="volume" :formatter="formatVolume"></el-table-column> -->
      <el-table-column label="相关新闻" width="500">
        <template  v-slot="scope">
          <el-row v-for="(item, index) in scope.row.news">
            <el-text class="w-150px mb-2" truncated>
              <el-link @click="goToNewsDetail(item.id)" type="primary">{{ item.title }}</el-link>
            </el-text>
          </el-row>
          <el-text v-if="scope.row && scope.row.news && scope.row.news.length === 0">没有相关新闻</el-text>
          <el-link class="MoreNews" 
                   v-else-if="scope.row && scope.row.news && scope.row.news.length >= 3" 
                   type="default"
                   @click="goToMoreNews(scope.row.stockId)"
          >查看更多</el-link>
        </template>
      </el-table-column>

    </el-table>
  </div>
</template>

<script setup>
// 导入所需模块
import {onMounted, ref, computed, watch} from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { useCounterStore } from "@/stores/counter.js";
import { getKlineDataApi, getStockRealDataApi } from '@/api/tushare';
import { getWatchlistApi } from '@/api/watchlist';
import { listThreeNewsApi,getjournalismRanking} from "@/api/request"
import router from "@/router/index"


// K线图相关设置
let showKPicture = ref(1);
const ts_code = ref("000001.SZ");
const chartDom = ref(null);
const recommendedNews = ref([]);
const searchQuery = ref("");
const stocks = ref([]);
const store = useCounterStore()
const userMessage = ref(store.UserMessage)

let emptyMessage=ref("请先登录")
watch(()=>store.UserMessage,()=>{
  if(!sessionStorage.getItem("token")){
    emptyMessage.value="请先登录"
    return
  }
  emptyMessage.value="自选股列表为空"
},{deep:true,immediate:true})

// 切换K线图类型
function ChangePicture(index) {
  showKPicture.value = index;
  getKData();
}

// 获取推荐新闻
function getRecommandNews() {
  getjournalismRanking().then(res => {
    recommendedNews.value = res.records;
  });
}

// 初始化K线图
onMounted(() => {
  getKData();
  // loadRecommendedNews(); // 加载推荐新闻
  // loadSampleStocks(); // 加载虚拟股票数据
  getWatchList()
  getRecommandNews()
});

// 绘制K线图
const draw = (chartDom, rawData) => {
  const myChart = echarts.init(chartDom);
  let option;

  const upColor = '#ec0000';
  const downColor = '#00da3c';
  const upBorderColor = '#8A0000';
  const downBorderColor = '#008F28';

  const data0 = splitData(rawData);

  function splitData(rawData) {
    const categoryData = [];
    const values = [];
    for (let i = 0; i < rawData.length; i++) {
      categoryData.push(rawData[i].splice(0, 1)[0]);
      values.push(rawData[i]);
    }
    return {
      categoryData: categoryData,
      values: values
    };
  }

  function calculateMA(dayCount) {
    const result = [];
    let i = 0, len = data0.values.length;
    for (; i < len; i++) {
      if (i < dayCount) {
        result.push('-');
        continue;
      }
      let sum = 0;
      for (let j = 0; j < dayCount; j++) {
        sum += +data0.values[i - j][1];
      }
      result.push(sum / dayCount);
    }
    return result;
  }

  option = {
    title: {
      text: '',
      left: 0
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['K线', 'MA5', 'MA10', 'MA20', 'MA30']
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '15%'
    },
    xAxis: {
      type: 'category',
      data: data0.categoryData,
      boundaryGap: false,
      axisLine: {onZero: false},
      splitLine: {show: false},
      min: 'dataMin',
      max: 'dataMax'
    },
    yAxis: {
      scale: true,
      splitArea: {
        show: true
      }
    },
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        show: true,
        type: 'slider',
        top: '90%',
        start: 0,
        end: 100
      }
    ],
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: data0.values,
        itemStyle: {
          color: upColor,
          color0: downColor,
          borderColor: upBorderColor,
          borderColor0: downBorderColor
        }
      },
      {
        name: 'MA5',
        type: 'line',
        data: calculateMA(5),
        smooth: true,
        lineStyle: {opacity: 0.5}
      },
      {
        name: 'MA10',
        type: 'line',
        data: calculateMA(10),
        smooth: true,
        lineStyle: {opacity: 0.5}
      },
      {
        name: 'MA20',
        type: 'line',
        data: calculateMA(20),
        smooth: true,
        lineStyle: {opacity: 0.5}
      },
      {
        name: 'MA30',
        type: 'line',
        data: calculateMA(30),
        smooth: true,
        lineStyle: {opacity: 0.5}
      }
    ]
  };

  option && myChart.setOption(option);
};

// 获取K线数据
const getKData = () => {
  getKlineDataApi(showKPicture.value, ts_code.value).then(res => {
    const kData = [];
    let needItem = ["trade_date", "open", "close", "low", "high"];
    let indexList = [];
    let fields = res.fields;

    // 获取需的字段索引
    for (let i = 0; i < needItem.length; i++) {
      let index = fields.indexOf(needItem[i]);
      indexList.push(index);
    }

    // 获取数据
    for (let i = 0; i < res.items.length; i++) {
      let item = [];
      item.push(formatDate(res.items[i][indexList[0]]));
      for (let j = 1; j < indexList.length; j++) {
        item.push(res.items[i][indexList[j]]);
      }
      kData.push(item);
    }

    draw(chartDom.value, kData);
  });
};

// 格式化日期
function formatDate(dateString) {
  let year = dateString.slice(0, 4);
  let month = dateString.slice(4, 6);
  let day = dateString.slice(6, 8);
  return `${year}/${parseInt(month)}/${parseInt(day)}`;
}

// 股票管理相关方法
const deleteStock = (id) => {
  stocks.value = stocks.value.filter(stock => stock.id !== id);
};


// 跳转到新闻详细页面
const goToNewsDetail = (id) => {
  router.push({
    path: "/journalismContent",
    query: {
      jourId: id
    }
  })
};


// 格式化增长比例
function formatRatio(value) {
  let ratio = value.ratio;
  if (ratio > 0) {
    return `+${ratio.toFixed(2)}%`;
  } else if (ratio < 0) {
    return `${ratio.toFixed(2)}%`;
  } else {
    return "0.00%";
  }
}

// 格式化成交量
function formatVolume(item) {
  let value = item.volume;
  if (value >= 100000000) {
    return (value / 100000000).toFixed(2) + '亿';
  } else if (value >= 10000000) {
    return (value / 10000000).toFixed(2) + '千万';
  } else if (value >= 1000000) {
    return (value / 1000000).toFixed(2) + '百万';
  } else if (value >= 10000) {
    return (value / 10000).toFixed(2) + '万';
  } else {
    return value;
  }
}

// 根据股票名称或者代码对股票进行筛选
const filteredStocks = computed(() => {
  const search = searchQuery.value.toLowerCase();
  return stocks.value.filter(stock => {
    return stock.name.toLowerCase().includes(search) || stock.ts_code.toLowerCase().includes(search);
  });
});

// 获取自选股列表及其相关新闻
function getWatchList() {
  // 未登录状态，不用获取自选股
  if (!userMessage.value || !userMessage.value.id) {
    console.log("未登录状态，不用获取自选股");
    return
  }
  let param = {userId: userMessage.value.id}
  getWatchlistApi(param).then(res => {
    let records = res.records;
    let stockCodes = [];
    let promises = [];
    if (records && records.length > 0) {
      for (let i = 0; i < records.length; i++) {
        let stock = {}
        stock.stockId = records[i].stockId
        stock.name = records[i].stockName
        stock.ts_code = records[i].stockCode
        stockCodes.push(records[i].stockCode)
        // 获取股票新闻
        let promise = listThreeNewsApi(stock.stockId).then(res => {
          stock.news = res
          stocks.value.push(stock);
        })
        // console.log(stock);
        promises.push(promise);
      }
    }
    // 等待所有 listThreeNewsApi 的异步操作完成
    Promise.all(promises).then(() => {
      getStockRealData();
    });
  });
}

// 获取自选股票的实时数据
const getStockRealData = () => {
  console.log("stock长度：", stocks.value.length);

  for (let i = 0; i < stocks.value.length; i++) {
    let stock = stocks.value[i];
    getStockRealDataApi(stock.ts_code).then(res => {
      let data = res.data;
      stock.date = data.t;
      stock.high = data.h;
      stock.low = data.l;
      stock.open = data.o;
      stock.pre_close = data.yc;
      stock.price = data.p;
      stock.volume = data.v;
      stock.ratio = data.pc;
      stock.status = data.pc > 0 ? 'up' : 'down';
      // console.log("获取实时数据后：stock", stock);
    })
  }
}


function goToMoreNews(stockId) {
  store.HeaderNavigate=2
    router.push({
        path: "/journalism",
        query: {
            stockId: stockId
        }
    })
}

// 跳转到股票详情页面
function ToStockMessagePage(row) {
  console.log(row)
  router.push({
    path: "/stockDetail",
    query: {
      stockId: row.stockId
    }
  })
}

// 表格行样式
const rowStyle = () => {
  return {
    cursor: 'pointer',
  }
}
</script>

<style scoped>
.container {
  display: flex;
  /* 使用 Flexbox 布局 */
  justify-content: space-between;
  /* 子元素水平分布 */
  margin: 20px;
  /* 页面边缘的间距 */
  flex-wrap: wrap;
  /* 当窗口缩小时，允许子容器换行 */
}

.left-container {
  width: 48%;
  /* 每个容器占 48% 宽度，可根据需要调整 */
  margin-bottom: 20px;
  /* 在换行后，每个容器之间有间距 */
  border: 1px solid #ccc;
  /* 容器边框 */
  border-radius: 10px;
  /* 圆角边框 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 阴影效果 */
}

.right-container {
  width: 48%;
  /* 每个容器占 48% 宽度，可根据需要调整 */
  margin-bottom: 20px;
  /* 在换行后，每个容器之间有间距 */
}

.Kpicture,
.recommend-container {
  padding: 15px;
}

.pictureClassfiy {
  display: flex;
  border-left: 7px solid #3377ff;
  padding-left: 16px;
  font-size: 16px;
  font-weight: 800;
  margin-bottom: 8px;
}

.pictureClassfiy div {
  margin-left: 5%;
  cursor: pointer;
}

.Picture {
  margin-top: 17px;
  border-top: 1px solid #b3acac;
  overflow: hidden;
}

.PictureContent {
  width: 100%;
  height: 100%;
  max-width: 100%;
  /* 确保图表最大宽度适应容器 */
  min-height: 400px;
  /* 设置一个最小高度 */
}

.recommend-container {
  position: relative;
  margin-bottom: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.recommendSection {
  background-color: #f9f9f9;
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.recommendSection h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 10px;
}

.recommendList {
  list-style-type: none;
  padding: 0;
  flex-grow: 1;
  overflow-y: auto;
}

.recommendList li {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.recommendList li:hover {
  background-color: #e7e7e7;
}

.recommendTitle {
  font-size: 18px;
  color: #333;
}

.recommendTime {
  font-size: 14px;
  color: #888;
}

.stock-management-container {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 20px;
  background-color: #f9f9f9;
  margin-top: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stock-management-container h3 {
  font-size: 24px;
  color: #333;
  margin-bottom: 15px;
}

.stock-management-container .el-button {
  justify-content: center;
  text-align: center;
}

.filter {
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: left;
}

th {
  background-color: #f2f2f2;
}

.active-border {
  border-bottom: 3px solid #3377ff;
}

.normal-border {
  border-bottom: 3px solid white;
}

.MoreNews{
  text-decoration: underline;
  font-size: 13px;
  color: #570093a6;
}
</style>